#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
#include <string.h>

bool FileExist(const char *file){
	FILE* hFile = fopen(file,"rb");
	if(hFile == NULL){
		fclose(hFile);
		return false;
	}
	return true;
}
unsigned long GetLength(const char * file_path,int bIsAsccii){
	unsigned long size;
	FILE * hFile;
	if(bIsAsccii)
		hFile = fopen(file_path,"r");
	else
		hFile = fopen(file_path,"rb");
	fseek(hFile,0,SEEK_END);
	size = ftell(hFile);
	fclose(hFile);
	return size;
}

int main(int argc, char *argv[])
{
	char name_buf[100] = {0};
	FILE * hFile,* hDestFile;
	unsigned char * buffer = 0;
	unsigned long ulSize = 0;
	int nCount,nStartPos = 1,bIsAsccii = 0,num = 1;
	if(argc >= 2){
		if(argv[1][0] == '\\' && toupper(argv[1][1]) == 'H'){
			if(argc != 4 && argc != 5){
				printf("The syntax of the command is incorrect.\n");
				return EXIT_FAILURE;
			}
			sprintf(name_buf,"mergeh %s %s %s",argv[2],argv[3],((argc == 5)?argv[4]:""));
			system(name_buf);
			return 0;
		}
		if(FileExist(argv[argc - 1])){
			printf("The file '%s' exists, do you want to continue? (Yes/No):",argv[argc - 1]);
			if(toupper(getchar()) != 'Y')
				return 0;
		}
		if(argv[1][0] == '\\' && toupper(argv[1][1]) == 'A'){
			hDestFile = fopen(argv[argc - 1],"w");
			nStartPos = bIsAsccii = 2;
		}else{
			hDestFile = fopen(argv[argc - 1],"wb");
		}
		if(argc - 1 == 1){
			sprintf(name_buf,"%s.split.part%d",argv[argc - 1],1);
			for(nCount = 2;FileExist(name_buf);++nCount,++num){
				sprintf(name_buf,"%s.split.part%d",argv[argc - 1],nCount);
			}
		}else{
			num = argc - 1;
		}
		for(nCount = nStartPos;nCount < num;++nCount){
			if(argc - 1 == 1){
				sprintf(name_buf,"%s.split.part%d",argv[argc - 1],nCount - nStartPos + 1);
				printf("test: %s\n",name_buf);
				ulSize = GetLength(name_buf,bIsAsccii);
				if(FileExist(name_buf)){
					if(bIsAsccii)
						hFile = fopen(name_buf,"r");
					else
						hFile = fopen(name_buf,"rb");
					printf("Part %s (%ld) has been merged\n",name_buf,ulSize);
				}
			}else{
				ulSize = GetLength(argv[nCount],bIsAsccii);
				if(bIsAsccii)
					hFile = fopen(argv[nCount],"r");
				else
					hFile = fopen(argv[nCount],"rb");
				printf("Part %s (%ld) has been merged\n",argv[nCount],ulSize);
			}
			buffer = (unsigned char *)malloc(ulSize);
			fread(buffer,sizeof(unsigned char),ulSize,hFile);
			fwrite(buffer,sizeof(unsigned char),ulSize,hDestFile);
			fclose(hFile);
			free(buffer);
			
		}
		fclose(hDestFile);
		printf("%s has been created\n",argv[argc - 1]); 
	}else{
		printf(
		"The syntax of the command is incorrect.\n"
		"merge [\\A] <source> <source> [more] <destination>\n"
		"merge [\\A] <source>\n"
		"merge \\H <destination> <source name> [<meta number>]\n"
		);
	}
	return 0;
}